package com.zcoj.util;

import com.zcoj.core.model.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class FileUtil {

    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 将字符串写入指定文件(当指定的父路径中文件夹不存在时，会最大限度去创建，以保证保存成功！)
     *
     * @param res            原字符串
     * @param filePath 文件路径
     * @return 成功标记
     */
      public static boolean string2File(String res, String filePath) {
        boolean flag = true;
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;
        try {
            File distFile = new File(filePath);
            if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs();
            bufferedReader = new BufferedReader(new StringReader(res));
            bufferedWriter = new BufferedWriter(new FileWriter(distFile));
            char buf[] = new char[1024];         //字符缓冲区
            int len;
            while ((len = bufferedReader.read(buf)) != -1) {
                bufferedWriter.write(buf, 0, len);
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
            return flag;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    /**
     * 获取文件扩展名，不带 .
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * Java文件操作 获取不带扩展名的文件名
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }



    public static File uploadImg(MultipartFile file,String filePath){
        String suffix = getExtensionName(file.getOriginalFilename());
        if(suffix.equals("png")||suffix.equals("jpg")||suffix.equals("jpeg")){
            return upload(file,filePath);
        }else {
            return null;
        }
    }

    /**
     * 将文件名解析成文件的上传路径
     */
    public static File upload(MultipartFile file, String filePath) {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmssS");
        String name = getFileNameNoEx(file.getOriginalFilename());
        String suffix = getExtensionName(file.getOriginalFilename());
        String nowStr = "-" + format.format(date);
        try {
            String fileName = name + nowStr + "." + suffix;
            String path = filePath + fileName;
            // getCanonicalFile 可解析正确各种路径
            File dest = new File(path).getCanonicalFile();
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                if (!dest.getParentFile().mkdirs()) {
                    System.out.println("was not successful.");
                }
            }
            // 文件写入
            file.transferTo(dest);
            return dest;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * @method: [uploadProblemTestcase]
     * @param: [file , filePath 绝对地址 , caseNumber]
     * @returns: java.io.File
     * @description:        题目测试案例上传
     * @author: chen.bin
     * @version: 1.0.0
     * @date 2023/3/16 11:14
     **/

    public static File uploadProblemTestcase(MultipartFile file, String filePath,Integer caseNumber) {

        String suffix = getExtensionName(file.getOriginalFilename());
        if( Objects.nonNull(suffix)&&!(suffix.equals("in")||suffix.equals("out"))){
            throw new RuntimeException("题目测试案例文件后缀名不合法");
        }
        try {
            String fileName = caseNumber.toString() + "." + suffix;
            String path = filePath + fileName;
            // getCanonicalFile 可解析正确各种路径
            File dest = new File(path).getCanonicalFile();
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                if (!dest.getParentFile().mkdirs()) {
                    System.out.println("was not successful.");
                }
            }
            //判断文件是已经存在
            if(dest.exists()){
                throw new RuntimeException("题目文件已经存在");
            }
            // 文件写入
            file.transferTo(dest);
            return dest;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * @method: [toDiskPath]
     * @param: [absolutePath]
     * @returns: java.lang.String
     * @description:       将网络地址转换成磁盘真实地址  http://127.0.0.1:8080/file/md/img/IMG_0304-20230316085006878.JPG  ->/Users/zcoj/file/md/img/IMG_0304-20230316085006878.JPG
     * @author: chen.bin
     * @version: 1.0.0
     * @date 2023/3/16 10:00
     **/
    public static String toDiskPath(String absolutePath){
            String[] tempPath =absolutePath.split("/");
            boolean isFile=false;
            StringBuilder realPath= new StringBuilder();
            for (String s : tempPath) {
                if (isFile) {
                    realPath.append("/").append(s);
                }
                if (s.equals("file")) {
                    isFile = true;
                }
            }
            return Constants.File.Root_Dir_RE.getPath()+ realPath;
    }





}
